import React, {Component} from 'react';
import {
    View,
    TextInput,
    Text,
    TouchableOpacity,
    StyleSheet,
    FlatList,
    ScrollView
}from 'react-native';
import {withNavigation} from "react-navigation";
import Tool from '../../../components/Tool';
import Style from '../../../components/Style';
import Header from '../../../components/Header';
import Icon from 'react-native-vector-icons/Ionicons';
import IconItem from 'react-native-vector-icons/MaterialIcons';
import NoticeDetail from "../../Base/Notice/Detail";
 const {color, fontSize  , tip} =Style;
 //一定要放在头部,不然会报错 header:<SearchHeaderHtml/>
const SearchHeaderHtml= withNavigation(class SearchHeaderHtml extends Component{
    render() {
        return (
            <View style={[styles.headView,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]}>
                <IconItem name={'search'} size={18} style={{marginLeft: 30, resizeMode: 'stretch' ,color:color.gray}}/>
                <TextInput style={{flex:1,paddingLeft:-5,color:color.gray}}
                           placeholder={'搜索'}
                           underlineColorAndroid='transparent'
                           keyboardType='web-search'
                           returnKeyType='search'
                           onChangeText={(query) =>{
                               this.props.this.setState({
                                   query:query,
                               });// 当内容改变时执行该方法
                           }}
                           onEndEditing={()=>this.props.this._selectText()}
                />
                <IconItem name={'keyboard-voice'} size={18} style={{color:color.blue,}}/>
            </View>
        );
    }
});
export default class SearchScreen extends Component {
    static navigationOptions = {
    };
    constructor(props){
        super(props);
        this.state={
            historyList:[],
            query:'',
            searchVisible:true,
            kpiList:[],
            noticeList:[],
        }
    }
    componentDidMount() {
        this._selectHistory();
    }
    _selectHistory(){
        let _this = this;
        Tool.fetchJson(Tool.appPath.mkst+'select/getSelectHistory','',function (data) {
            if(data.state){
                _this.setState({
                    historyList:data.info,
                });
            }
        },function (error) {

        },function () {

        });
    }
    _selectText(){
        let _this = this,
            pageNum=1,
            pageSize= 15;
       _this.setState({searchVisible:false});
        Tool.fetchJson(Tool.appPath.mkst+'select/getSelectDetail?info='+this.state.query+'&&pageNum='+pageNum+'&&pageSize='+pageSize,'',function (data) {
            if(data.state){
                _this.setState({
                    kpiList:data.info.index,
                    noticeList:data.info.advertise
                })
            }
            _this._selectHistory();
          //  alert(JSON.stringify(_this.state.noticeList));
        },function (error) {
        },function () {
        });
    }
    _deleteHistory(){
        let _this= this;
        Tool.fetchJson(Tool.appPath.mkst+'select/deleteSelectHistory','',function (data) {
            if(data.state){
                _this.setState({
                    historyList:[]
                });
            }
        },function (error) {

        },function () {

        });
    }
    _setQuery(title){
        let _this = this;
        //setState是异步
        _this.setState({
            query:title,
            kpiList:[],
            noticeList:[],
        } ,() => {
            _this._selectText();
        });
    }
    render(){
        return(
            <View style={styles.contentView}>
               <SearchHeader thisSelf={this}/>
                {this.state.searchVisible?
                <View style={styles.searchView}>
                    <View>
                        {
                            this.state.historyList.map((item,index)=>
                                <HistoryItem this={this} key={`SearchItem_${index}`} title={item}/>
                            )
                        }
                    </View>

                    <View style={styles.clearView}>
                        <TouchableOpacity onPress={()=>this._deleteHistory()}>
                            <Text style={{color:color.gray,fontSize:fontSize.small}}>清空历史记录</Text>
                        </TouchableOpacity>
                    </View>
               </View>
                    :
                <View style={[styles.searchView]}>
                    <ScrollView style={{marginLeft:10,marginRight:10}}>
                        <FlatList
                            data= {this.state.kpiList.list}
                            keyExtractor={(item,index) => `IndexKpiSearch_${index}`}
                            renderItem={({item}) =>
                                <KpiItem title={item.indexName}  code={item.indexCode} type={item.indexType}/>
                            }
                        />
                        <FlatList
                            data= {this.state.noticeList.list}
                            keyExtractor={(item,index) => `IndexNoticeSearch_${index}`}
                            renderItem={({item}) =>
                                <NoticeItem item={item}/>
                            }
                        />
                        {
                            (this.state.noticeList.total== 0 && this.state.kpiList.total == 0)
                            || (this.state.noticeList == '' && this.state.kpiList == '')?
                                <View style={{height:30,justifyContent:'center'}}><Text style={{textAlign:'center',color:color.gray}}>未查询到数据!</Text></View>:null
                        }
                    </ScrollView>
                </View>
                }
            </View>
        )
    }
}
const KpiItem = withNavigation(class KpiItem extends  Component{
    render(){
        let url = this.props.type==3?"ImportFollow":"OperateIndex";
        return(
            <View style={styles.searchItem}>
                <TouchableOpacity
                    style={{ flexDirection: 'row',}}
                    onPress={() => this.props.navigation.navigate(url,{headerTitle:this.props.title,indexCode:this.props.code})}>
                    <View style = {{flex:1}}>
                        <Text style={styles.titleStyle}>{this.props.title}</Text>
                    </View>
                    <View>
                        <Text numberOfLines={1} style={[styles.conStyle,{alignSelf:'flex-end',color:color.blue}]}>指标</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
})
const NoticeItem = withNavigation(class NoticeItem extends Component{
    render() {
        let item = this.props.item;
        return (
            <View style={styles.searchItem}>
                <TouchableOpacity
                    style={{flexDirection:'row'}}
                    onPress={() => this.props.navigation.navigate('NoticeDetail',{headerTitle:item.name,noticeId:item.id})}>
                    <View style={{flex: 1}}>
                        <Text style={styles.titleStyle}>{item.name}</Text>
                    </View>
                    <View>
                        <Text style={[styles.conStyle, {alignSelf: 'flex-end', color: color.green}]}>公告</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
});
class HistoryItem extends Component{
    _select(){
        let title = this.props.title;
        this.props.this._setQuery(title);
    }
    render(){
        return(
            <View style={styles.itemView}>
                <TouchableOpacity
                    onPress={()=>this._select()}
                    style={{ flexDirection:'row',  }}>
                     <Icon name={'md-time'} size={13} style={{marginLeft:10,marginRight:10}}/>
                     <Text style={{fontSize:fontSize.normal}}>{this.props.title}</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

class SearchHeader extends Component {
    render() {
        let _this = this.props.thisSelf;
        return (
            <View style={[styles.headView,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]}>
                <IconItem name={'search'} size={18} style={{marginLeft: 30,color:color.gray}}/>
                <TextInput style={{flex:1,padding:0,fontSize:fontSize.small,color:color.gray}}
                           placeholder={'搜索'}
                           selectionColor={color.green}
                           underlineColorAndroid='transparent'
                           keyboardType='web-search'
                           returnKeyType='search'
                           value={_this.state.query}
                           onChangeText={(query) =>{
                               _this.setState({
                                   query:query,
                                   kpiList:[],
                                   noticeList:[],
                                   searchVisible:true,
                               });// 当内容改变时执行该方法
                           }}
                           onSubmitEditing ={()=>_this._selectText()}
                           onFocus={()=>{
                               _this.setState({
                                   searchVisible:true,
                               });
                           }}
                />
                <IconItem name={'keyboard-voice'} size={18} style={{color:color.blue,}}/>
            </View>
        );
    }
};
const styles = StyleSheet.create({
    headView:{
        backgroundColor:'#fbfbfb',
        height:30,
    },
    contentView:{
        backgroundColor:color.lightGray,
        flex:1,
    },
    itemView:{
        borderBottomWidth:1,
        borderColor:color.lightGray,
        borderStyle:'dotted',
        height:30,
        justifyContent:'center',
    },
    clearView:{
        height:30,
        justifyContent:'center', //垂直居中
        alignItems:'center',
    },
    searchView:{
        marginTop:10,
        backgroundColor:'#fbfbfb',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#D7D7D7',
        borderStyle:'dotted',
        shadowColor:'#272727',
        shadowOffset:{ width:2, height:2 },
        shadowOpacity:0.2,
        shadowRadius:1,
        elevation: 4,
    },
    searchItem:{
        borderBottomWidth: 1,
        borderColor: '#D7D7D7',
        borderStyle: 'dotted',

        paddingBottom: 10,
        paddingTop: 10
    }
})